<?php

include 'confidential_settings.php';
// This include contains 5 variables:
//  - db_name: database name
//  - table_name_x: table name
//  - username: username
//  - password: password
//  - localhost: host name

function get_corr_value_day($year,$month,$day){
	include 'wat_corrections.php';

	$ret_corr_value = 0;
	for($i=0; $i< count($corr_year); $i++){
		if((trim($corr_year[$i]) == trim($year))&&(trim($corr_month[$i]) == trim($month))&&(trim($corr_day[$i]) == trim($day))){
			$ret_corr_value = $corr_value[$i];
			return $ret_corr_value;
		}
	}
	return $ret_corr_value;
}


$dbh=mysql_connect ($localhost, $username, $password) or die('Cannot connect to the database because: ' . mysql_error());

mysql_select_db ($db_name) or die(mysql_error()); 

$result = mysql_query("SELECT YEAR(date_entered), DAY(date_entered), MONTH(date_entered), SUM(val) FROM $table_name_wat GROUP BY YEAR(date_entered), MONTH(date_entered), DAY(date_entered)");

mysql_close($dbh);


mysql_data_seek ($result , 0);

$max = 0;
$min = 1000000;
$max_date = '';
$min_date = '';
$start_date = '';
$avg = 0;
$nb = 0;
while($row = mysql_fetch_array($result)){
	$corr_value_tmp = get_corr_value_day($row['YEAR(date_entered)'],$row['MONTH(date_entered)'],$row['DAY(date_entered)']);
	$tmp = $row['SUM(val)'];
	$tmp = ($tmp/100)  + ($corr_value_tmp);
	if($start_date = ''){
		$start_date = $row['DAY(date_entered)'] . '/' . $row['MONTH(date_entered)'] . '/' . $row['YEAR(date_entered)'];
	}
	if($tmp > $max){
		$max = $tmp;
		$max_date = $row['DAY(date_entered)'] . '/' . $row['MONTH(date_entered)'] . '/' . $row['YEAR(date_entered)'];
	}
	if($tmp < $min){
		$min = $tmp;
		$min_date = $row['DAY(date_entered)'] . '/' . $row['MONTH(date_entered)'] . '/' . $row['YEAR(date_entered)'];
	}
	$avg = $avg + $tmp;
	$nb = $nb + 1;
}
$sum = $avg;
$avg = $avg / $nb;


 
mysql_data_seek ($result , 0);


echo 'WATER CONSUMPTION [m3]<br/>';


// display statistics
echo '<br/>Statistics<br/>';
echo 'Start date' . "\t" . $start_date . '<br/>';
echo 'Nb of days' . "\t" . $nb . '<br/>';
echo 'Sum' . "\t" . $sum . '<br/>';
echo 'Avg' . "\t" . $avg . '<br/>';
echo 'Min' . "\t" . $min . '<br/>';
echo 'Min day' . "\t" . $min_date . '<br/>';
echo 'Max' . "\t" . $max . '<br/>';
echo 'Max day' . "\t" . $max_date . '<br/>';
echo '<br/><br/>';



// display actual values
while($row = mysql_fetch_array($result)){
	$corr_value_tmp = get_corr_value_day($row['YEAR(date_entered)'],$row['MONTH(date_entered)'],$row['DAY(date_entered)']);
	$tmp = $row['SUM(val)'];
	$tmp = ($tmp/100) + ($corr_value_tmp);
	echo $row['DAY(date_entered)'];
	echo '/';
	echo $row['MONTH(date_entered)'];
	echo '/';
	echo $row['YEAR(date_entered)'];
	echo "\t";
	echo $tmp;
	echo '<br/>';
}


?>
